package com.example.AIstudy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.AIstudy.DTO.ProsetDTO;
import com.example.AIstudy.domain.CuoTiJi;
import com.example.AIstudy.domain.Exercise;
import com.example.AIstudy.domain.LevelRecord;
import com.example.AIstudy.domain.ProSet;
import com.example.AIstudy.exception.AIstudyException;
import com.example.AIstudy.service.CuoTiJiService;
import com.example.AIstudy.service.ExerciseService;
import com.example.AIstudy.service.ProSetService;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/exercise")
@Api(tags = "习题信息管理API")
public class ExerciseController {

    @Autowired
    ExerciseService exerciseService;

    @Autowired
    ProSetService proSetService;

    @Autowired
    ProSetController proSetController;

    //分页获取练习题
    @ApiOperation("根据条件查询习题")
    @GetMapping("")
    public IPage<Exercise> findExercise(@ApiParam("题目类别")@RequestParam(value = "category",required = false) String category,
                                        @ApiParam("题目")@RequestParam(value = "problem",required = false) String problem,
                                        @ApiParam("页码")@RequestParam(defaultValue = "0")Integer pageNum,
                                        @ApiParam("每页记录数") @RequestParam(defaultValue = "10")Integer pageSize){

        Map<String,Object> condition=new HashMap<>();
        if(problem!=null) {
            condition.put("problem",problem);
        }
        if(category!=null) {
            condition.put("category",category);
        }
        return exerciseService.findExercise(condition, pageNum,pageSize);
    }

    @ApiOperation("增加习题（可以增加一道大题，即同时增加很多小题，要保证第一题在第一个）")
    @PostMapping ("")
//    @PreAuthorize("hasAnyAuthority('all')")
    void insertExercise(@RequestBody List<Exercise> exercises)throws AIstudyException{
        exerciseService.insertExercise(exercises);
    }

    //获取子练习题（属于同一道大题）
    @ApiOperation("获取子练习题")
    @GetMapping("/sonProblem/{ids}")
    public List<Exercise> findSonExercise(@ApiParam("子题字符串")@PathVariable List<Integer>ids){
        return exerciseService.findSonExercise(ids);
    }

    @PutMapping("")
    @ApiOperation("修改练习题，允许在一道大题上进行修改，即同时修改很多小题")
//    @PreAuthorize("hasAnyAuthority('all')")
    public void updateExercise(@RequestBody List<Exercise> exercises) throws AIstudyException{
       int size=exercises.size();
        System.out.println("修改习题的数量是："+size);
        exerciseService.updateExercise(exercises);
    }

    //批量删除练习题
    //如果在前端直接删除一道大题的话，需要在前端接卸子题的ID并封装
    @ApiOperation("批量删除练习题")
    @DeleteMapping ("/{questionID}")
//    @PreAuthorize("hasAnyAuthority('all')")
    public void deleteExercise(@ApiParam("题目的ID")@PathVariable List<Integer>questionID) throws AIstudyException{
        System.out.println("修改习题的数量是："+questionID.size());
        exerciseService.deleteExercise(questionID);
    }
    @ApiOperation("根据错题推荐题库中的题目")
    @GetMapping("/recommend")
    public List<Exercise> getRecommendExe(@ApiParam("用户ID")@RequestParam(value = "userID")Integer userID,
                                     @ApiParam("错题的esID")@RequestParam(value = "cuotiESID")String cuotiESID,
                                     @ApiParam("错题的类型")@RequestParam(value = "category")String category,
                                     @ApiParam("选择题的推荐方式")@RequestParam(value = "recommendWay",required = false)String recommendWay)throws AIstudyException{
        try{
                //执行python的环境
                String anacondaUrl="python";
                String pythonapiURL=new File(".").getCanonicalPath()+"/python-api/main/intelligent_recommendation(1).py";
                String[]arg=null;
                if(category.equals("yuedu")){
                    if(recommendWay==null)recommendWay="reading_type";
                    arg=new String[]{anacondaUrl, pythonapiURL,category,cuotiESID,recommendWay};
                }else{
                    arg=new String[]{anacondaUrl, pythonapiURL,category,cuotiESID.toString()};
                }
                Process proc = Runtime.getRuntime().exec(arg);
                int res = proc.waitFor();
                System.out.println(res);
                if (res == 0) {
                    System.out.println("成功执行");
                    //成功执行 获取输出信息
                    String line=null;
                    BufferedReader inData = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gb2312"));
                    StringBuilder builder=new StringBuilder();
//                    //新创建一个套题对象
//                    ProSet proSet=new ProSet();
//                    proSet.setStuID(userID);
                    //获取套题对应的题目ID
                    List<String>esidList=new ArrayList<>();
                    while ((line = inData.readLine()) != null){
//                        Exercise exercise=exerciseService.selectByesID(line);
                        //获取到每个返回的题目ID
                        esidList.add(line);
                        //获取到题目子题对应的ID
                    }
                    inData.close();
                    return exerciseService.getExerviceByesList(esidList);
                    //将套题信息插入到数据库中
//                    proSet.setExerciseList(exerciseIDs);
//                    proSetService.insertProSet(proSet);
                    //根据套题的ID把需要巩固的题目封装成套题
//                    return proSetController.findProsetDetailByID(proSet.getId());
                }else{
                    System.out.println("执行错误");
                    //未成功执行 获取错误输出信息
                    String line=null;
                    BufferedReader inError = new BufferedReader(new InputStreamReader(proc.getErrorStream(), "gb2312"));
                    while ((line = inError.readLine()) != null) {
                        System.out.println(line);
                        throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"智能分析错题失败");
                    }
                    inError.close();
                }
                proc.waitFor();
            }catch (IOException | InterruptedException e){
                System.out.println(e.getMessage());
                throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"智能分析错题失败");
            }
        return null;
    }
}
